<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="分类名称" prop="className">
        <el-input
          v-model="queryParams.className"
          placeholder="请输入分类名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['goods:goodsClass:add']"
        >新增分类</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="goodsClassList"
      row-key="id"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column prop="className" align="center" label="分类名称" ></el-table-column>
      <el-table-column prop="sort"  align="center" label="排序" ></el-table-column>
      <el-table-column prop="status"  align="center" label="状态" >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center"  class-name="small-padding fixed-width">
        <template  slot-scope="scope">
          <el-button
            v-if="scope.row.level == 1"
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAddChild(scope.row)"
            v-hasPermi="['goods:goodsClass:add']"
          >新增子类</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['goods:goodsClass:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['goods:goodsClass:remove']"
          >删除</el-button>

        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改商品分类对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item v-if="form.level==2" label="上级分类" prop="parentId">
          <el-select style="width: 100%" v-model="form.parentId" placeholder="请选择">
            <el-option
              v-for="item in goodsClassList"
              :key="item.id"
              :label="item.className"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分类名称" prop="className">
          <el-input v-model="form.className" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="排序号"  prop="sort"  >
          <el-input-number style="width: 100%" v-model="form.sort" :min="0" />
        </el-form-item>
        <el-form-item label="分类图片" prop="pictureId">
          <div class="picture" @click="handleSelector" >
            <el-image v-if="form.previewPath" style="width:100%;" :src="baseUrl+form.previewPath"></el-image>
            <i v-else style="font-size: 16px" class="el-icon-plus"></i>
          </div>
        </el-form-item>
        <el-form-item label="分类状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 图片选择器 -->
    <picture-selector
      ref="selector"
      :open="selector"
      :multiple="1"
      @input="getCheckedPicture"
      @close="closeSelector"
    ></picture-selector>

  </div>
</template>

<script>
import { listGoodsClass, getGoodsClass, delGoodsClass, addGoodsClass, updateGoodsClass,changeClassStatus } from "@/api/goods/goodsClass";
import PictureSelector from "@/views/picture/file/selector";
export default {
  name: "GoodsClass",
  components: {
    PictureSelector
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品分类表格数据
      goodsClassList: [],
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 是否展开
      expand: false,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //图片选择器
      selector:false,
      // 分类状态：0为正常，1为停用字典
      statusOptions: [],
      //选中的文件
      checkedFileList:[],
      baseUrl:process.env.VUE_APP_BASE_API,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        parentId: null,
        className: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        className: [
          { required: true, message: "分类名称不能为空", trigger: "blur" },
          { max: 20, message: '分类名称长度不能超过20个字符', trigger: 'blur' }
        ],
        parentId: [
          { required: true, message: "上级分类不能为空", trigger: "blur" }
        ],
        pictureId: [
          { required: true, message: "分类图片不能为空", trigger: "blur" }
        ],
        sort: [
          { required: true, message: "排序号不能为空", trigger: "blur" },
          { pattern: /^[0-9]\d*$/, message: "排序号必须为正整数", trigger: "blur" },
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_normal_disable").then(response => {
      this.statusOptions = response.data;
    });
  },
  methods: {
    /** 查询商品分类列表 */
    getList() {
      this.loading = true;
      listGoodsClass(this.queryParams).then(response => {
        this.goodsClassList = this.handleTree(response.data, "id");
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        parentId: null,
        className: null,
        sort: 0,
        pictureId: null,
        previewPath:undefined,
        status: "0",
        level: null
      };
      this.resetForm("form");
      this.checkedFileList=[];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加一级分类";
      this.form.parentId = 0;
      this.form.level =1;
    },
    /** 新增按钮操作 */
    handleAddChild(row) {
      this.reset();
      this.open = true;
      this.title = "添加子类";
      this.form.parentId = row.id;
      this.form.level = 2;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getGoodsClass(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商品分类";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateGoodsClass(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGoodsClass(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$confirm('是否确认删除商品分类"' + row.className + '"吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delGoodsClass(id);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 更改分类状态 */
    handleStatusChange(row){
      let text = row.status === "0" ? "启用" : "停用";
      this.$confirm('确认要"' + text + '""' + row.className + '"分类吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return changeClassStatus(row.id, row.status);
      }).then(() => {
        this.getList();
        this.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    /** 打开图片选择器 */
    handleSelector(){
      this.selector=true;
    },
    getCheckedPicture(checkedFileList){
      this.checkedFileList=checkedFileList;
      if(this.checkedFileList.length>0){
        this.form.pictureId=this.checkedFileList[0].id;
        this.form.previewPath = this.checkedFileList[0].previewPath;
        this.$refs.form.clearValidate("pictureId")
      }
    },
    //关闭选择器
    closeSelector(){
      this.selector=false;
    },
  }
};
</script>
<style lang="scss" scoped>
 .picture{
   background-color: #fbfdff;
   border: 1px dashed #c0ccda;
   -webkit-box-sizing: border-box;
   box-sizing: border-box;
   width: 120px;
   height: 120px;
   cursor: pointer;
   line-height: 118px;
   vertical-align: top;
   text-align: center;
 }
</style>
